var t = null;
var up = false;
var tempo = 100;
 

var campus = {
  init: function() {
    var MAX = 5;
    var $ = function(id)
    {
      return document.getElementById(id);
    }

    var clone = function(obj) {
      var val = {};
      for (key in obj) {
        val[key] = obj[key];
      }
      return val;
    }
    
    var MAP_TYPE = [
    G_NORMAL_MAP,
    G_SATELLITE_MAP
    ];
    var Stock = {
      id: "",
      title: "新建校园地图",
      lng: "103.0727471",
      lat: "33.9434726",
      width: '600',
      height: '400',
      mapType: 1,
      zoom: 2
    }
    var container = [];
    for(var i = 0; i < MAX; i ++) {
      container[i] = null;
    }

    function createMap(dom, stockMap) {

      var plus = "<img alt='加' src='img/plus.png'/>";
      var minus = "<img alt='加' src='img/minus.png'/>";
      
      var title = "<h5>标题:<input type=\"text\" id=\"" + stockMap.id + "_title\" value=\"" + stockMap.title + "\" /></h5>";
      var mapDom = "<div id=\"" + stockMap.id + "\" class=\"campusMap\" style=\"width:" + stockMap.width + "px;height:" + stockMap.height + "px;\"></div>";
      var mapSave = "<a href=\"javascript:void(0)\" id=\"" + stockMap.id + "_save\" alt=\"保存\">保存</a>";
      var mapCopy = "<a href=\"javascript:void(0)\" id=\"" + stockMap.id + "_copy\" alt=\"复制\">复制</a>";
      var mapDelete = "<a href=\"javascript:void(0)\" id=\"" + stockMap.id + "_delete\">删除</a>";
      var mapHeight = "高度:<span id=\"" + stockMap.id + "_Height\">" + stockMap.height + "</span> <img src=\"img/plus.png\" id=\"" + stockMap.id + "_Height_add\" />&nbsp;<img src=\"img/minus.png\" id=\"" + stockMap.id + "_Height_minus\"/>";
      var mapWidth = "宽度:<span id=\"" + stockMap.id + "_Width\">" + stockMap.width + "</span>&nbsp;<img src=\"img/plus.png\" id=\"" + stockMap.id + "_Width_add\"/>&nbsp;<img src=\"img/minus.png\" id=\"" + stockMap.id + "_Width_minus\"/>";

      var wrapper = "<div id=\"" + stockMap.id + "_wrapper\">" + mapDom + "</div>";
      var div = document.createElement('div');
      div.className = "stockMap";
      div.id = "container" + stockMap.id;

      div.innerHTML = "<p class=\"nav\"> " + mapSave + mapDelete + mapCopy + mapHeight + mapWidth + "</p>" + title + mapDom;
      dom.appendChild(div);
      stockMap.div = div;
      var labels = ['Height', 'Width'];
      var acts = ['add', 'minus'];
      for(var i = 0; i < labels.length; i ++)
        for(var j = 0; j < acts.length; j ++){
          id = stockMap.id + "_" + labels[i] + "_" + acts[j];
          $(id).idx = stockMap.idx;
          $(id).stock = stockMap;
          $(id).i = i;
          $(id).j = j;
          if(j == 0) {
            $(id).innerHTML = plus;
          } else {
            $(id).innerHTML = minus;
          }
          function Act(id) {
            function add(num){
              return num + 1;
            }
            function minus(num) {
              if(num > 1) return num - 1;
              return num;
            }

            var func = add;
            var obj = $(id);
            var stock = obj.stock;
            var j = obj.j;
            var i = obj.i;
            id = obj.id;
            obj = $("map" + obj.idx);
            if(j == 1) func = minus
 
            if(i == 1) {
              var width = obj.style.width;
              width = parseInt(width.substring(0, width.length - 2));
              width = func(width);
              obj.style.width = width + "px";
              $(obj.id + "_Width").innerHTML = width;
              stock.width = width;
            }else{
              var height = obj.style.height;
              height = parseInt(height.substring(0, height.length - 2));
              height = func(height);
              obj.style.height = height + "px";
              $(obj.id + "_Height").innerHTML = height;
              stock.height = height;
            }
            map.checkResize();
          }
          window.Auto = function(id) {
            clearTimeout(t)
            if(up) {
              up = false;
              return
            }
            Act(id);
            t = setTimeout("Auto(\"" + id + "\")", tempo);
          }
          GEvent.addDomListener($(id), 'mousedown', function(event) {
            clearTimeout(t)
            up = false;
            var obj = event.target;
            t = setTimeout("Auto(\"" + event.target.id + "\")", 500);
          });
          GEvent.addDomListener($(id), 'click', function(event) {
            var obj = event.target;
            Act(obj.id);
          });

          GEvent.addDomListener($(id), 'mouseup', function(event) {
            up = true;
            clearTimeout(t)
          });
        }

      var copyDom = $(stockMap.id + "_copy");
      copyDom.stock = stockMap;
      GEvent.addDomListener(copyDom, "click", function(event) {
        var stockMap = event.target.stock;
        var map = container[stockMap.idx].map;
        var tmp = "";
        var save = {};
        save.id = stockMap.id;
        var center = map.getCenter();
        save.lat = center.lat();
        save.lng = center.lng();
        save.title = $(stockMap.id + "_title").value;
        mapType = map.getCurrentMapType();
        for(var j = 0; j < MAP_TYPE.length; j ++)
        {
          if(mapType == MAP_TYPE[j]) {
            save.mapType = j;
            break;
          }
        }
        save.zoom = map.getZoom();
        save.width = $(stockMap.id).style.width;
        save.width = parseInt(save.width.substring(0, save.width.length - 2));
        save.height = $(stockMap.id).style.height;
        save.height = parseInt(save.height.substring(0, save.height.length - 2));
 
        for(var i = 0; i < container.length; i++) {
          if(container[i] == null) {
            stock = clone(save);
            stock.id = "map" + i;
            stock.idx = i;
            container[i] = createMap($("map"), stock);
            break;
          }
        }
   
      });
 
      var deleteDom = $(stockMap.id + "_delete");
      deleteDom.stock = stockMap;
      GEvent.addDomListener(deleteDom, "click", function(event) {
        var stock = event.target.stock;
        dom.removeChild(stock.div);
        container[stock.idx] = null;
        clearTimeout(stock.t);
        stock.t = null;
      });
      var saveDom = $(stockMap.id + "_save");
      saveDom.stock = stockMap;
      GEvent.addDomListener(saveDom, "click", function(event) {
        var save = {};
        var str = "";
        var stockMap = $(event.target.id).stock;
        var map = event.target.map;
        save.id = stockMap.id;
        str += "id = " + save.id + "\n";
        var center = map.getCenter();
        save.lat = center.lat();
        str += "lat = " + save.lat + "\n";
        save.lng = center.lng();
        str += "lng = " + save.lng + "\n";
        save.title = $(stockMap.id + "_title").value;
        str += "title = " + save.title + "\n";
        mapType = map.getCurrentMapType();
        for(var i = 0; i < MAP_TYPE.length; i ++)
        {
          if(mapType == MAP_TYPE[i]) {
            save.mapType = i;        
            break;
          }
        }
        str += "mapType = " + save.mapType + "\n";
        save.zoom = map.getZoom();
        str += "zoom = " + save.zoom + "\n";
        save.width = $(stockMap.id).style.width;
        save.width = parseInt(save.width.substring(0, save.width.length - 2));
        str += "width = " + save.width + "\n";
        save.height = $(stockMap.id).style.height;
        save.height = parseInt(save.height.substring(0, save.height.length - 2));
        str += "height = " + save.height + "\n";
        ret.save = save;
      });
      var map = new GMap2($(stockMap.id));
      map.setMapType(MAP_TYPE[stockMap.mapType]);
      var latlng = new GLatLng(stockMap.lat, stockMap.lng);
      map.setCenter(latlng, stockMap.zoom);
      map.enableScrollWheelZoom();
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());
      saveDom.map = map;
      var ret = {
        map: map,
        stock: stockMap
      }
      return ret;
    }

    var Add = function(){
      for(var i = 0; i < container.length; i++) {
        if(container[i] == null) {
          var stock = clone(Stock);
          stock.id = "map" + i;
          stock.idx = i;
          container[i] = createMap($("map"), stock);
          break;
        }
      }
    }

    var Update = function(){
      var str = "";
      for(var i = 0; i < container.length; i++) {
        if(container[i] != null) {
          var stockMap = container[i].stock;
          var map = container[i].map;
          var tmp = "";
          var save = {};
          save.id = stockMap.id;
          var center = map.getCenter();
          save.lat = center.lat();
          save.lng = center.lng();
          save.title = $(stockMap.id + "_title").value;
          mapType = map.getCurrentMapType();
          for(var j = 0; j < MAP_TYPE.length; j ++)
          {
            if(mapType == MAP_TYPE[j]) {
              save.mapType = j;        
              break;
            }
          }
          save.zoom = map.getZoom();
          save.width = $(stockMap.id).style.width;
          save.width = parseInt(save.width.substring(0, save.width.length - 2));
          save.height = $(stockMap.id).style.height;
          save.height = parseInt(save.height.substring(0, save.height.length - 2));
          tmp = "{id:\"" + save.id + "\", lat: \"" + save.lat + "\", lng: \"" + save.lng + "\", title: \"" + save.title + "\", mapType: \"" + save.mapType + "\", zoom: " + save.zoom + ", width: " + save.width + ", height: " + save.height + "}";
          if(str)
            str += "," + tmp;
          else
            str += tmp;
        }
      }
     return str;
     }

    var Preview = function()
    {
      var str = Update();
      var key = $('hidden').value;
      var url = "/campus?key=" + key;
      GDownloadUrl(url, function(data) {
        if (!key) key = data;
        window.open("/campus?act=preview&key=" + data);
      }, "json=[" + str + "]");
      return false;
    }
 
    var Code = function()
    {
      var str = Update();
      var key = $('hidden').value;
      var url = "/campus?key=" + key;
      GDownloadUrl(url, function(data) {
        if (!key) key = data;
        window.open("/campus?act=code&key=" + data);
      }, "json=[" + str + "]");
      return false;
    }

    var Iframe = function()
    {
      var str = Update();
      var key = $('hidden').value;
      var url = "/campus?key=" + key;
      GDownloadUrl(url, function(data) {
        if (!key) key = data;
        window.open("/campus?act=iframe&key=" + data);
      }, "json=[" + str + "]");
      return false;
    }
    var IframeCode = function()
    {
      var str = Update();
      var key = $('hidden').value;
      var url = "/campus?key=" + key;
      GDownloadUrl(url, function(data) {
        if (!key) key = data;
      $('codeCon').style.display = "";
      $("textarea").value = "<iframe src=\"" + window.location + "?act=iframe&key=" + data + "\"></iframe>";
      }, "json=[" + str + "]");
      return false;
    }


    var CloseCode = function()
    {
      $('codeCon').style.display = "none";
    }

    GEvent.addDomListener($("add"), 'click', Add);
    GEvent.addDomListener($('preview'), 'click', Preview);
    GEvent.addDomListener($('code'), 'click', Code);
    GEvent.addDomListener($('iframe'), 'click', Iframe);
    GEvent.addDomListener($('iframeCode'), 'click', IframeCode);
    GEvent.addDomListener($('closeCode'), 'click', CloseCode);
    Add();
  /*
   var newStock = clone(Stock);
   newStock.id = "map1";
   newStock.title = "北京地图";
   createMap($("map"), newStock);
   */
  }
};

window.onload = function()
{
  campus.init();
}

